package com.ctshk.rpc.order.ship.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.order.ship.dto.*;
import com.ctshk.rpc.order.ship.entity.*;
import com.ctshk.rpc.order.ship.manager.ShipOrderManager;
import com.ctshk.rpc.order.ship.mapper.*;
import com.ctshk.rpc.order.ship.req.ShipOrderReceiptReq;
import com.ctshk.rpc.order.ship.service.IShipOrderReceiptService;
import com.ctshk.rpc.ship.dto.ShipReserveListDTO;
import com.ctshk.rpc.ship.req.ShipProductIsRecommendedReq;
import com.ctshk.rpc.ship.req.ShipZJProductIsRecommendedReq;
import com.ctshk.rpc.ship.service.IShipProductService;
import com.ctshk.rpc.system.dto.SysDepartmentDTO;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.ISysDepartmentService;
import com.ctshk.rpc.system.service.ISysUserService;
import com.github.houbb.heaven.util.util.CollectionUtil;
import com.google.common.collect.Lists;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

import java.time.LocalDateTime;
import java.time.Period;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 船票订单收据 服务实现类
 * </p>
 *
 * @author 刘蕾
 * @since 2021-03-31
 */
@DubboService
public class ShipOrderReceiptServiceImpl extends ServiceImpl<ShipOrderReceiptMapper, ShipOrderReceipt> implements IShipOrderReceiptService {

    @DubboReference
    private ISysUserService iSysUserService;


    @DubboReference
    private IShipProductService iShipProductService;

    @DubboReference
    private ISysDepartmentService iSysDepartmentService;

    @Autowired
    ShipOrderReceiptMapper shipOrderReceiptMapper;

    @Autowired
    ShipOrderMapper shipOrderMapper;

    @Autowired
    ShipOrderCollectionMapper shipOrderCollectionMapper;

    @Autowired
    ShipOrderInsuranceMapper shipOrderInsuranceMapper;

    @Autowired
    ShipOrderRouteMapper shipOrderRouteMapper;

    @Override
    public Result add(Long orderId, TokenUser user) {
        UserDTO userDTO = iSysUserService.loadUserByParam(user.getId(), 1);
        SysDepartmentDTO sysDepartmentDTO = iSysDepartmentService.queryByUserId(user.getId());
        ShipOrderReceipt shipOrderReceipt = new ShipOrderReceipt();
        Long id = IdWorker.getId();
        shipOrderReceipt.setId(id);
        shipOrderReceipt.setOrderId(orderId);
        shipOrderReceipt.setBranch(sysDepartmentDTO.getDeptCode() + "-" + sysDepartmentDTO.getTitle());
        shipOrderReceipt.setCreateId(user.getId());
        shipOrderReceipt.setGmtModified(LocalDateTime.now());
        shipOrderReceipt.setIsDeleted(IsDeletedCode.NO.getCode());
        shipOrderReceipt.setModifiedId(user.getId());
        shipOrderReceipt.setGmtModified(LocalDateTime.now());
        shipOrderReceipt.setReceiptNo(ShipOrderManager.getReceiptNumer(sysDepartmentDTO.getDeptCode(), userDTO.getEmployeeNumber()));
        shipOrderReceipt.setLicenseNo(ShipOrderManager.LICENSE_NO);
        shipOrderReceipt.setSupportNo(ShipOrderManager.SUPPORT_NO);
        shipOrderReceiptMapper.insert(shipOrderReceipt);
        return Result.success(id);
    }

    @Override
    public Result edit(ShipOrderReceiptReq req, TokenUser tokenUser) {
        UpdateWrapper<ShipOrderReceipt> shipOrderReceiptUpdateWrapper = new UpdateWrapper<>();
        shipOrderReceiptUpdateWrapper.lambda().eq(ShipOrderReceipt::getId, req.getId());
        shipOrderReceiptUpdateWrapper.lambda().set(StringUtils.isNotBlank(req.getAttention()), ShipOrderReceipt::getAttention, req.getAttention());
        shipOrderReceiptUpdateWrapper.lambda().set(StringUtils.isNotBlank(req.getGuest()), ShipOrderReceipt::getGuest, req.getGuest());
        shipOrderReceiptUpdateWrapper.lambda().set(StringUtils.isNotBlank(req.getPhone()), ShipOrderReceipt::getPhone, req.getPhone());
        shipOrderReceiptUpdateWrapper.lambda().set(StringUtils.isNotBlank(req.getRemark()), ShipOrderReceipt::getRemark, req.getRemark());
        shipOrderReceiptUpdateWrapper.lambda().set(ShipOrderReceipt::getGmtModified, LocalDateTime.now());
        shipOrderReceiptUpdateWrapper.lambda().set(ShipOrderReceipt::getModifiedId, tokenUser.getId());
        shipOrderReceiptMapper.update(null, shipOrderReceiptUpdateWrapper);

        return Result.success(req.getId());
    }

    @Override
    public Result info(Long orderId,TokenUser user) {
        /**查询订单信息*/
        ShipOrder shipOrder = shipOrderMapper.selectById(orderId);
        if (null == shipOrder) {
            return Result.failed(SystemError.SHIP_PRODUCT_11032);
        }
        QueryWrapper<ShipOrderReceipt> shipOrderReceiptQueryWrapper = new QueryWrapper<>();
        shipOrderReceiptQueryWrapper.lambda().eq(ObjectUtils.isNotNull(orderId), ShipOrderReceipt::getOrderId, orderId);
        ShipOrderReceipt shipOrderReceipt = shipOrderReceiptMapper.selectOne(shipOrderReceiptQueryWrapper);
        if (null == shipOrderReceipt) {
            return Result.failed(SystemError.SYS_411);
        }
        /**查询收款信息*/
        QueryWrapper<ShipOrderCollection> shipOrderCollectionQueryWrapper = new QueryWrapper<>();
        shipOrderCollectionQueryWrapper.lambda().eq(ShipOrderCollection::getOrderId, shipOrder.getId());
        List<ShipOrderCollection> shipOrderCollectionList = shipOrderCollectionMapper.selectList(shipOrderCollectionQueryWrapper);
        List<ShipOrderReceiptProductDTO> productList = new ArrayList<>();
        /**查询航班信息*/
        String[] split = shipOrder.getProductId().split(",");
        ShipZJProductIsRecommendedReq shipZJProductIsRecommendedReq = new ShipZJProductIsRecommendedReq();
        String companyName = "";
        String refundContent = "";
        for (String s : split) {
            ShipOrderReceiptProductDTO shipOrderReceiptProductDTO = new ShipOrderReceiptProductDTO();
            if(StringUtils.isNotBlank(shipOrder.getApiOrderNumber())){
                shipZJProductIsRecommendedReq.setProductId(s);
                List<ShipReserveListDTO> shipReserveListDTOS = iShipProductService.queryApiProductList(shipZJProductIsRecommendedReq);
                ShipReserveListDTO shipReserveListDTO = shipReserveListDTOS.get(0);
                companyName = shipReserveListDTO.getSupplierName();
                refundContent = shipReserveListDTO.getRefundContent();
                BeanUtils.copyProperties(shipReserveListDTO,shipOrderReceiptProductDTO);
            }else{
                ShipProductIsRecommendedReq shipProductIsRecommendedReq = new ShipProductIsRecommendedReq();
                shipProductIsRecommendedReq.setId(Long.valueOf(s));
                List<ShipReserveListDTO> shipReserveListDTOS = iShipProductService.queryReserveList(shipProductIsRecommendedReq, user,null);
                ShipReserveListDTO shipReserveListDTO = shipReserveListDTOS.get(0);
                companyName = shipReserveListDTO.getSupplierName();
                refundContent = shipReserveListDTO.getRefundContent();
                BeanUtils.copyProperties(shipReserveListDTO,shipOrderReceiptProductDTO);
            }
            productList.add(shipOrderReceiptProductDTO);
        }
        /**组装返回结果*/
        ShipOrderReceiptInfoDTO shipOrderReceiptInfoDTO = EntityUtil.copy(shipOrderReceipt, ShipOrderReceiptInfoDTO.class);
        shipOrderReceiptInfoDTO.setShipOrderReceiptCollectionList(EntityUtil.copyList(shipOrderCollectionList,ShipOrderReceiptCollectionDTO.class));
        shipOrderReceiptInfoDTO.setShipOrderReceiptProductList(productList);
        shipOrderReceiptInfoDTO.setCompanyName(companyName);
        shipOrderReceiptInfoDTO.setRefundContent(refundContent);
        return Result.success(shipOrderReceiptInfoDTO);
    }

    @Override
    public Result<List<InsuranceReceiptDTO>> insuranceReceipt(Long id, TokenUser currentUser) {
        List<InsuranceReceiptDTO> insuranceReceiptList = Lists.newArrayListWithExpectedSize(5);
        ShipOrder shipOrder = shipOrderMapper.selectById(id);
        if(shipOrder == null){
            throw new BusinessException(SystemError.SHIP_PRODUCT_11032);
        }

        //获取订单保险信息
        List<ShipOrderInsurance> insuranceList = shipOrderInsuranceMapper.selectList(Wrappers.<ShipOrderInsurance>lambdaQuery()
                .eq(ShipOrderInsurance::getOrderId, id));

        if(CollectionUtil.isNotEmpty(insuranceList)){
            for(ShipOrderInsurance insurance : insuranceList){
                ShipOrderRoute shipOrderRoute = shipOrderRouteMapper.selectOne(Wrappers.<ShipOrderRoute>lambdaQuery().eq(ShipOrderRoute::getOrderId, id)
                        .eq(ShipOrderRoute::getProductId, insurance.getProductId()));


                insuranceReceiptList.add(InsuranceReceiptDTO.builder().passenger(insurance.getPolicyHolderName()).agent("")
                        .insuranceNumber(insurance.getInsuranceNumber()).orderNumber(shipOrder.getOrderNumber())
                        .days(Period.between(insurance.getInsuranceStartDate().toLocalDate(), insurance.getInsuranceEndDate().toLocalDate()).getDays())
                        .depDate(Objects.isNull(shipOrderRoute)?null:shipOrderRoute.getDepTime().toLocalDate())
                        .productRoute(Objects.isNull(shipOrderRoute)?"":shipOrderRoute.getRouteName())
                        .insuranceCompany("").insurancePlan("").startDate(null)
                        .assuredList(obtainAssured(insurance))
                        .totalAmount(null)
                        .contactMobile("").startInsuranceDate(null).payWay("")
                        .receiptNumber("").productId(Long.valueOf(insurance.getProductId()))
                        .cardNumber("")
                        .build());
            }
        }
        return Result.success(insuranceReceiptList);
    }

    /**
     * 获取被保险人列表
     * @param insurance
     * @return
     */
    private List<AssuredInfo> obtainAssured(ShipOrderInsurance insurance) {
        return Lists.newArrayListWithExpectedSize(1);
    }
}
